package com.kehutong.common.math;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * Author:  peter
 * Date:    2020/7/8
 * Function:计算工具类
 */
public class CalculatorUtils {

    /**
     * 计算百分比
     */
    public static BigDecimal percentage(int part, int total) {
        if (total == 0) {
            return null;
        }
        return new BigDecimal(part)
                .multiply(new BigDecimal(100))
                .divide(new BigDecimal(total), 2, BigDecimal.ROUND_HALF_UP);
    }

    public static BigDecimal percentage(BigDecimal part, BigDecimal total) {
        // equals 有坑 scale不同时会为false
        if (BigDecimal.ZERO.compareTo(total) == 0) {
            return BigDecimal.ZERO;
        }
        return part.multiply(new BigDecimal(100)).divide(total, 2, BigDecimal.ROUND_HALF_UP);
    }


    /**
     * 获取数值为几位小数
     * 1 -> 0
     * 1.1 -> 1
     * 1.002 -> 3
     * 1.010 -> 2
     */
    public static int getDecimalPlace(BigDecimal num) {
        if (num == null) {
            throw new IllegalArgumentException();
        }
        // 去除末尾0
        String s = num.stripTrailingZeros().toPlainString();

        if (!s.contains(".")) {
            return 0;
        }

        return s.length() - s.indexOf(".") - 1;
    }

    /**
     * 格式化金额转为2位小数
     */
    public static BigDecimal formatMoney(BigDecimal a) {
        if (a == null) {
            return null;
        }
        return a.setScale(2, RoundingMode.DOWN);
    }

    public static String formatMoneyString(BigDecimal a) {
        BigDecimal money = formatMoney(a);
        if (money == null) {
            return null;
        }
        return money.toString();
    }
}
